// 保存API Key
document.getElementById('saveKey').addEventListener('click', async () => {
  const apiKey = document.getElementById('apiKey').value;
  await chrome.storage.sync.set({ deepseekApiKey: apiKey });
  document.getElementById('status').textContent = 'API Key 已保存';
  setTimeout(() => {
    document.getElementById('status').textContent = '';
  }, 2000);
});

// 保存显示原文的设置
document.getElementById('showOriginal').addEventListener('change', async (event) => {
  await chrome.storage.sync.set({ showOriginal: event.target.checked });
});

// 加载保存的设置
document.addEventListener('DOMContentLoaded', async () => {
  const { deepseekApiKey, showOriginal } = await chrome.storage.sync.get(['deepseekApiKey', 'showOriginal']);
  if (deepseekApiKey) {
    document.getElementById('apiKey').value = deepseekApiKey;
  }
  
  // 设置复选框状态，默认为true（显示原文）
  document.getElementById('showOriginal').checked = showOriginal !== undefined ? showOriginal : true;
  
  // 检查当前页面的翻译状态
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  try {
    const response = await new Promise((resolve, reject) => {
      chrome.tabs.sendMessage(tab.id, {
        action: 'getTranslationStatus'
      }, response => {
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError);
        } else {
          resolve(response);
        }
      });
    });
    
    // 根据翻译状态更新按钮
    updateButtonState(response.isTranslating);
  } catch (error) {
    // 如果出错（比如页面未加载完成），默认设置为未翻译状态
    updateButtonState(false);
  }
});

// 更新按钮状态的函数
function updateButtonState(isDisabled) {
  const translateButton = document.getElementById('translate');
  const stopButton = document.getElementById('stopTranslate');
  
  if (isDisabled) {
    translateButton.disabled = true;
    translateButton.style.backgroundColor = '#cccccc'; // 灰色背景
    translateButton.style.cursor = 'not-allowed';     // 禁用状态的鼠标样式
    stopButton.disabled = false;
    stopButton.style.backgroundColor = '#dc3545';     // 保持停止按钮为红色
    stopButton.style.cursor = 'pointer';
  } else {
    translateButton.disabled = false;
    translateButton.style.backgroundColor = '#0078d4'; // 恢复原来的蓝色
    translateButton.style.cursor = 'pointer';
    stopButton.disabled = true;
    stopButton.style.backgroundColor = '#cccccc';     // 停止按钮变灰
    stopButton.style.cursor = 'not-allowed';
  }
}

// 翻译按钮点击事件
document.getElementById('translate').addEventListener('click', async () => {
  const { deepseekApiKey } = await chrome.storage.sync.get('deepseekApiKey');
  if (!deepseekApiKey) {
    document.getElementById('status').textContent = '请先设置 API Key';
    return;
  }

  // 获取是否显示原文的设置
  const { showOriginal } = await chrome.storage.sync.get('showOriginal');

  updateButtonState(true); // 禁用翻译按钮，启用停止按钮

  document.getElementById('status').textContent = '正在启动翻译...';
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  
  try {
    // 向内容脚本发送消息
    const response = await new Promise((resolve, reject) => {
      chrome.tabs.sendMessage(tab.id, {
        action: 'translate',
        apiKey: deepseekApiKey,
        showOriginal: showOriginal !== undefined ? showOriginal : true
      }, response => {
        if (chrome.runtime.lastError) {
          reject(new Error(chrome.runtime.lastError.message));
        } else {
          resolve(response);
        }
      });
    });
    
    if (response.status === 'success') {
      window.close(); // 关闭弹出窗口
    } else if (response.status === 'error') {
      document.getElementById('status').textContent = '翻译失败: ' + response.message;
      // 恢复按钮状态
      updateButtonState(false);
    }
  } catch (error) {
    document.getElementById('status').textContent = '翻译失败: ' + error.message;
    // 恢复按钮状态
    updateButtonState(false);
  }
});

// 停止翻译按钮点击事件
document.getElementById('stopTranslate').addEventListener('click', async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  
  try {
    // 向内容脚本发送停止消息
    const response = await new Promise((resolve, reject) => {
      chrome.tabs.sendMessage(tab.id, {
        action: 'stopTranslate'
      }, response => {
        if (chrome.runtime.lastError) {
          reject(new Error(chrome.runtime.lastError.message));
        } else {
          resolve(response);
        }
      });
    });
    
    if (response.status === 'success') {
      document.getElementById('status').textContent = response.message;
      // 恢复按钮状态
      updateButtonState(false);
      // 关闭弹出窗口
      setTimeout(() => window.close(), 1000);
    }
  } catch (error) {
    document.getElementById('status').textContent = '停止失败: ' + error.message;
  }
}); 